package com.dnjn.happiness.emo.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dnjn.happiness.common.core.constant.Constants;
import com.dnjn.happiness.common.core.domain.KV;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.security.annotation.InnerAuth;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.emo.api.model.RiskVO;
import com.dnjn.happiness.emo.domain.Risk;
import com.dnjn.happiness.emo.domain.vo.RecordScore;
import com.dnjn.happiness.emo.service.IRiskService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 风控 前端控制器
 * </p>
 *
 * @author Amber
 * @since 2023-10-09
 */
@Tag(name = "emo Risk 风控", description = "风控")
@RestController
@RequestMapping("/risk")
public class RiskController extends BaseController {

    @Autowired
    protected IRiskService baseService;

    @InnerAuth
    @GetMapping("/getByRiskType/{rtype}")
    public R<Risk> getByRiskType(@PathVariable String rtype){
        return R.ok(baseService.getByRiskType(rtype));
    }

    @InnerAuth
    @GetMapping("/getRiskAll")
    public R<List<RiskVO>> getRiskAll(){
        List<Risk> listRisk = baseService.lambdaQuery().eq(Risk::getDeleted, "0").eq(Risk::getSelected, "Y").list();
        List<RiskVO> voList = new ArrayList<>();
        listRisk.forEach(item->{
            RiskVO riskVO = new RiskVO();
            BeanUtils.copyProperties(item,riskVO);
            voList.add(riskVO);
        });
        return R.ok(voList);
    }

    @RequiresPermissions("emo:risk:query")
    @GetMapping("/get/{id}")
    public AjaxResult get(@PathVariable Long id) {
        return success(baseService.getById(id));
    }

    @RequiresPermissions("emo:risk:add")
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody Risk domain) {
        domain.setCreateBy(SecurityUtils.getUsername());
        return toAjax(baseService.save(domain));
    }
    @RequiresPermissions("emo:risk:edit")
    @PutMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody Risk domain) {
        return toAjax(baseService.updateById(domain));
    }

    @RequiresPermissions("emo:risk:edit")
    @PutMapping("/editByIds")
    public AjaxResult editByIds(@Validated @RequestBody List<Risk> list) {
        long errCount = list.stream().filter(el ->BigDecimal.ZERO.compareTo(el.getWeight())>0).count();
        Assert.isTrue(errCount==0,"权重不能小于0");//!

        BigDecimal weight = list.stream().filter(el -> StringUtils.equals(el.getSelected(), "Y"))
                .map(Risk::getWeight).reduce(BigDecimal::add).get();
        Assert.isTrue(weight.compareTo(BigDecimal.ONE)<1,"无效权重和：" + weight);

        boolean flag = baseService.updateBatchById(list);
        return toAjax(flag);
    }
    @RequiresPermissions("emo:risk:remove")
    @DeleteMapping("/{pkIds}")
    public AjaxResult remove(@PathVariable Long[] pkIds) {
        baseService.removeBatchByIds(Arrays.asList(pkIds));
        return success();
    }
    @RequiresPermissions("emo:risk:list")
    @PostMapping("/list")
    public AjaxResult list() {
        List<Risk> list = baseService.lambdaQuery().eq(Risk::getDeleted, Constants.UNDELETED).list();
        return success(list);
    }

    @RequiresPermissions("emo:risk:query")
    @PostMapping("/pageAdmin")
    public AjaxResult pageAdmin() {
        List<Risk> list = baseService.lambdaQuery().eq(Risk::getDeleted, "0").list();
        return success(list);
    }

    @PostMapping("/page")
    public AjaxResult page() {
        List<Risk> list = baseService.lambdaQuery().eq(Risk::getDeleted, "0").list();
        return success(list);
    }
    @PostMapping("/export")
    public void export(HttpServletResponse response, Risk domain) {
        List<Risk> list = baseService.list(Wrappers.query(domain));
        ExcelUtil<Risk> util = new ExcelUtil<Risk>(Risk.class);
        util.exportExcel(response, list, "参数数据");
    }

    @GetMapping("/loadInfo")
    public AjaxResult loadInfo(Long userId) {
        List<RecordScore> list = baseService.loadInfo(userId);
        return success(KV.by("list", list).add("total", list.size()));
    }

}